package net.ys.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * @author: NMY
 * @Date: 2021/9/15
 * @Time: 8:33
 * 获取访问者ip地址
 */
@RestController
public class ClientController {

    @GetMapping("/client/info")
    public String clientInfo(HttpServletRequest request) {

        Enumeration<String> names = request.getHeaderNames();
        StringBuffer stringBuffer = new StringBuffer();
        String agent = request.getHeader("user-agent");
        String hh = "<br/>";
        if (agent.contains("curl") || agent.contains("Wget")) {
            hh = "\n";
        }
        while (names.hasMoreElements()) {
            String name = names.nextElement();
            stringBuffer.append(name + " ----> ").append(request.getHeader(name)).append(hh);
        }

        stringBuffer.append("clientIp --->").append(getIPAddress(request)).append(hh);
        return stringBuffer.toString();
    }

    private String getIPAddress(HttpServletRequest request) {
        String ip = null;
        String ipAddresses = request.getHeader("X-Forwarded-For");
        if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
            ipAddresses = request.getHeader("Proxy-Client-IP");
        }

        if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
            ipAddresses = request.getHeader("WL-Proxy-Client-IP");
        }

        if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
            ipAddresses = request.getHeader("HTTP_CLIENT_IP");
        }

        if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
            ipAddresses = request.getHeader("X-Real-IP");
        }

        if (ipAddresses != null && ipAddresses.length() != 0) {
            ip = ipAddresses.split(",")[0];
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
            ip = request.getRemoteAddr();
        }
        return ip.equals("0:0:0:0:0:0:0:1") ? "127.0.0.1" : ip;
    }
}
